package com.itheima.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.entity.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ：why
 * @description：
 * @version:
 */
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Result result = new Result(false,"登录失败!");
        if (exception instanceof LockedException) {
            result.setMessage("账户被锁定,请联系管理员!");
        } else if (exception instanceof CredentialsExpiredException) {
            result.setMessage("密码过期,请联系管理员!");
        } else if (exception instanceof AccountExpiredException) {
            result.setMessage("账户过期,请联系管理员!");
        } else if (exception instanceof DisabledException) {
            result.setMessage("账户被禁用,请联系管理员!");
        } else if (exception instanceof BadCredentialsException) {
            result.setMessage("用户名或密码输入错误!");
        }else if (exception instanceof UsernameNotFoundException) {
            result.setMessage("用户名不存在!");
        }
        writer.write(new ObjectMapper().writeValueAsString(result));
        writer.flush();
        writer.close();
    }
}
